package cn.genmer.test.security.utils;

import com.healthmarketscience.jackcess.*;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

public class AccessUtils {
    public static Database create(Database.FileFormat fileFormat, File file) throws IOException {
        Database database = DatabaseBuilder.create(fileFormat, file);
        return database;
    }

    @SneakyThrows
    public static Table createTable(Database database, String tableName, List<Field> fields) throws IllegalAccessException, InstantiationException, SQLException {
        TableBuilder tableBuilder = new TableBuilder(tableName);
//        Field[] Fields = clazz.getDeclaredFields();
        for (Field field : fields) {
//            CustomAnnotation anno = field.getAnnotation(CustomAnnotation.class);
//            if(anno!=null){
                if(StringUtils.isNotBlank(field.getName())){
                    tableBuilder.addColumn(new ColumnBuilder(field.getName()).setSQLType(transSqlType(field)).toColumn());
                }
//            }
        }
        Table table = tableBuilder.toTable(database);
        return table;
    }

    public static Integer transSqlType(Field field){
        String fieldType = "";
//        String fieldType = field.getFieldType().toString();
        switch (fieldType.toUpperCase()) {
            case "DATETIME":
//                return Types.TIME;
            case "INTEGER":
//                return Types.NUMERIC;
            case "DOUBLE":
            case "NUMERIC":
            case "DECIMAL":
            case "FLOAT":
//                return Types.DOUBLE;
            case "BLOB":
//                return Types.VARCHAR;
//                return Types.BLOB;
            case "STRING":
            default:
//              根据属性大小判断使用的类型
                Integer length = 255;
//                Integer length = field.getLength();
                if (length == null || length > 255){
                    return Types.LONGVARCHAR;
                } else {
                    return Types.VARCHAR;
                }
        }
    }
}
